﻿var oracledb = require('oracledb');
var dbConfig = require('./dbconfig');

function doConnect(cb) {
	oracledb.getConnection(
		{
			user          : dbConfig.user,
			password      : dbConfig.password,
			connectString : dbConfig.connectString
		},
		cb);
};

function doRelease(conn) {
	conn.release(function (err) {
		if (err)
			console.error(err.message);
	});
};

function doQuery(conn,sql,param, cb) {
	console.log('sql='+sql+', param='+param);
	conn.execute(
		sql,
		param, // A bind variable parameter is needed to disambiguate the following options parameter
		// otherwise you will get Error: ORA-01036: illegal variable name/number
		{ outFormat: oracledb.OBJECT }, // outFormat can be OBJECT or ARRAY.  The default is ARRAY
		function(err, result)
		{
			if (err) {
				return cb(err, conn);
			} else {
				console.log("----- Cities beginning with 'S' (OBJECT output format) --------");
				console.log(result.rows);
				return cb(null, conn,result.rows);
			}
		});
};

function doSelect(sql,param,callback){
	var async = require('async');
	async.waterfall([
		doConnect,
		function(conn,cb) {
			cb(null, conn, sql, param);
		},
		doQuery
	],function(err,conn,result){
		if (err) { console.error("In waterfall error cb: ==>", err, "<=="); }
		else{callback(result);}
		if (conn){ doRelease(conn);}
	});
};

function doSelect_Test(){
	doSelect("select * from tab",{},function(result){
		console.log(result);
	});
};

module.exports.doSelect = doSelect;

module.exports.doSelect_Test = doSelect_Test;

